package com.sl.hx.shop.ui.mine.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.ali.auth.third.core.model.Session;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.trade.biz.login.AlibcLogin;
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback;
import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;
import com.sl.hx.shop.R;
import com.sl.hx.shop.base.BaseActivity;
import com.sl.hx.shop.base.BaseTakePhotoActivity;
import com.sl.hx.shop.bean.HeadBean;
import com.sl.hx.shop.bean.ImageUrlBean;
import com.sl.hx.shop.bean.NickName;
import com.sl.hx.shop.bean.eventSetPhone;
import com.sl.hx.shop.constant.AppConfig;
import com.sl.hx.shop.constant.SPUKey;
import com.sl.hx.shop.ui.mine.contacts.SettingContacts;
import com.sl.hx.shop.ui.mine.presnter.SettingPresenter;
import com.sl.hx.shop.utils.CleanMessageUtil;
import com.sl.hx.shop.utils.NotifySetting;
import com.sl.hx.shop.utils.SPUtils;
import com.sl.hx.shop.utils.ToastUtil;
import com.sl.hx.shop.view.dialog.PpwSelectPicture;
import com.sl.hx.shop.widget.SwitchView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Notification.EXTRA_CHANNEL_ID;
import static android.provider.Settings.EXTRA_APP_PACKAGE;

public class SettingActivity extends BaseTakePhotoActivity<SettingContacts.view, SettingPresenter>
        implements SettingContacts.view, TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.icon)
    RelativeLayout icon;
    @BindView(R.id.tvnickname)
    TextView tvnickname;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.tvcache)
    TextView tvcache;
    @BindView(R.id.nickname)
    RelativeLayout nickname;
    @BindView(R.id.setnum)
    RelativeLayout setnum;
    @BindView(R.id.bindwechat)
    RelativeLayout bindwechat;
    @BindView(R.id.sw_taobao)
    SwitchView swTaobao;
    @BindView(R.id.sw_push)
    SwitchView swPush;
    @BindView(R.id.cache)
    RelativeLayout cache;
    @BindView(R.id.feedback)
    RelativeLayout feedback;
    @BindView(R.id.ll_user_info)
    LinearLayout mLlUserInfo;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;

    private TakePhoto mTakePhoto;
    //图片压缩参数
    private CompressConfig mCompressConfig;
    private CropOptions cropOptions;  //裁剪参数
    private PpwSelectPicture mPpwSelectPicture;
    //选择的图片的地址集合
    private String headImageUrl = null;
    private Uri imageUri;  //图片保存路径


    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected SettingPresenter createPresenter() {
        return new SettingPresenter(mContext);
    }

    @Override
    protected void init() {
        initPictureSelectPop();//图片pop
        initSwitch();//滑动条
        checkCache();//缓存大小
        mTakePhoto = getTakePhoto();
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(false).create();
        mCompressConfig = new CompressConfig.Builder().setMaxSize(100 * 1024).setMaxPixel(800).create();
        EventBus.getDefault().register(this);

        mPresenter.getUserInfo();
    }

    //设置昵称页面数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getChnagedName(String nickname){
        tvnickname.setText(nickname);
    }
    //设置手机号页面数据
    @Subscribe (threadMode = ThreadMode.MAIN)
    public void getChnagedPhone(eventSetPhone eventSetPhone){
        phone.setText(eventSetPhone.getPhone());
    }

    @OnClick({R.id.back, R.id.icon, R.id.nickname, R.id.setnum, R.id.bindwechat, R.id.sw_taobao, R.id.sw_push, R.id.cache, R.id.feedback, R.id.logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            //选择头像
            case R.id.icon:
                mPpwSelectPicture.showAtLocation(mLlUserInfo, Gravity.BOTTOM, 0, 0);
                mPpwSelectPicture.setBackgroundAlpha(this, 0.5f);
                break;
            //昵称
            case R.id.nickname:
                startActivityForResult(new Intent(this, NickNameActivity.class), 1);
                break;
            case R.id.setnum:
                startActivityForResult(new Intent(this, SetPhoneActivity.class), 2);
                break;
            //绑定微信
            case R.id.bindwechat:
                break;
            //清除缓存
            case R.id.cache:
                CleanMessageUtil.clearAllCache(mContext);
                checkCache();
                ToastUtil.showShort(this, "清除缓存成功");
                break;
            case R.id.feedback:
                toActivity(FeedbackActivity.class);
                break;
            case R.id.logout:
                SPUtils.getInstance().remove(AppConfig.ID);
                SPUtils.getInstance().remove(AppConfig.PHONE);
                ToastUtil.showShort(mContext, "操作成功");
                finish();
                break;
        }
    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        headImageUrl = result.getImage().getCompressPath();
        Glide.with(mContext).load(headImageUrl).into(iv_icon);
        mPresenter.uploadHeadImg(headImageUrl);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
        Glide.with(mContext).load(headImageUrl).into(iv_icon);
    }

    @Override
    public void changeHeadImgSuccess(ImageUrlBean imageUrlBean) {
        ToastUtil.showShort(mContext, "更改头像成功");
    }

    @Override
    public void ShowUserInfo(HeadBean headBean) {
        if (headBean.getNick()!=null) {
            tvnickname.setText(headBean.getNick() + "");
        }
        phone.setText(headBean.getPhone()+"");
        Glide.with(this).load(headBean.getLogo()).into(iv_icon);
    }

    private void initPictureSelectPop() {
        mPpwSelectPicture = new PpwSelectPicture(this);
        mPpwSelectPicture.setOnItemClickListener(new PpwSelectPicture.OnItemClickListener() {
            @Override
            public void onItemClick(View v) {

                switch (v.getId()) {

                    case R.id.tv_cancel:
                        mPpwSelectPicture.dismiss();
                        break;

                    case R.id.tv_album:
                        mPpwSelectPicture.dismiss();
                        imageUri = getImageCropUri();
                        mTakePhoto.onEnableCompress(mCompressConfig, true);
                        mTakePhoto.onPickFromGallery();
                        break;

                    case R.id.tv_new_picture:
                        mPpwSelectPicture.dismiss();
                        File file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".png");
                        if (!file.getParentFile().exists())
                            file.getParentFile().mkdirs();
                        Uri imageUri = Uri.fromFile(file);
                        mTakePhoto.onEnableCompress(mCompressConfig, true);
                        mTakePhoto.onPickFromCapture(imageUri);
                        break;

                }
            }
        });
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    private void initSwitch() {
        //淘宝授权滑动条
        swTaobao.setOnCheckedChangeListener(new SwitchView.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchView switchView, boolean isChecked) {
                //String tbIsLogin = SPUtils.getInstance().getString(SPUKey.TBUSERID);
                if (isChecked) {
                    TbLogin();
                } else {
                    Tblogout();
                }
            }
        });

        //通知滑动条
        swPush.setChecked(SPUtils.getInstance().getBoolean(SPUKey.ISRECEIVEMESSAGE, true));
        swPush.setOnCheckedChangeListener(new SwitchView.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchView switchView, boolean isChecked) {
                if (isChecked) {
                    //跳转设置页开启通知
                    NotifySetting.gotoNotifySet(mContext);
                } else {
                    ToastUtil.showShort(SettingActivity.this, "关闭通知");
                }
                SPUtils.getInstance().put(SPUKey.ISRECEIVEMESSAGE, isChecked);
            }
        });
    }

    //缓存大小
    private void checkCache() {
        try {
            tvcache.setText(CleanMessageUtil.getTotalCacheSize(mContext));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //淘宝授权登录
    private void TbLogin() {
        AlibcLogin alibcLogin = AlibcLogin.getInstance();
        alibcLogin.showLogin(new AlibcLoginCallback() {
            @Override
            public void onSuccess(int i) {
                ToastUtil.showShort(SettingActivity.this, "授权成功");
                //SPUtils.getInstance().put(SPUKey.TBUSERID,"tbLoginSuccess");
                //swTaobao.setChecked(true);
            }

            @Override
            public void onFailure(int code, String msg) {
                ToastUtil.showShort(SettingActivity.this, "授权失败");
                swTaobao.setChecked(false);
            }
        });
    }

    //淘宝退出登录
    private void Tblogout() {
        AlibcLogin alibcLogin1 = AlibcLogin.getInstance();
        alibcLogin1.logout(new AlibcLoginCallback() {
            @Override
            public void onSuccess(int i) {
                ToastUtil.showShort(SettingActivity.this, "取消授权");
                swTaobao.setChecked(false);
            }

            @Override
            public void onFailure(int i, String s) {
                ToastUtil.showShort(SettingActivity.this, "取消授权失败");
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //共用Contacts导致出现下面方法,在这页面没用

    @Override
    public void showtoast(String message) {

    }

    @Override
    public void setphoneSuccess(String mphone) {

    }


}
